/**
 * @desc:商品列表
 * @author：elvis
 */

import React, { useState, useEffect } from "react";
import useEventListener from "@/hooks/useEventListener";
import { Modal, Button, message, Popover } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import CommonTable from "@/components/CommonTable";
import SystemTableGoods from "../component/SystemTableGoods";
import CommonLoading from "@/components/CommonLoading";
import FooterToolbar from "@/components/FooterToolbar";
import CommonPage from "@/components/CommonPagination";
import SmartSetChannel from "../component/SmartSetChannel";
import EditChannelModal from "../component/EditChannelModal";
import CertificateModal from "../component/CertificateModal";
import TakeGoodsTemplateModal from "../component/TakeGoodsTemplateModal";
import { EditOutlined } from "@ant-design/icons";
import { formatAmount } from "@/utils/utils.jsx";
import {
	affectNums,
	getSystemGoodList,
	queryChannelStatistic,
	updateOrderGoods,
	changeSysGoodsType,
	delUpCertificate,
	delTakeTemplate
} from "../../service";
import { findIndex, pull, remove, find } from "lodash";
import { useRef } from "react";
const { confirm } = Modal;

export default ({ divEl, query, roleType, updateTime }) => {
	//商品类型
	const goodsType = query.deliverType;

	//商品列表
	const [goodsList, setGoodsList] = useState([]);

	// 智能设置和渠道设置弹框
	const [visible, setVisible] = useState(1);

	//当前操作的行信息
	const [item, setItem] = useState({});

	//选中的行id数组
	const [selectRowkeys, setSelectRowkeys] = useState([]);

	//分页
	const [pages, setPages] = useState({
		current: 1,
		pageSize: 100,
		total: 0
	});

	const [loading, setLoading] = useState(false);

	const [scrollHeight, setScrollHeight] = useState(600);

	const btnEl = useRef(null);

	useEffect(() => {
		setSelectRowkeys([]);
		setPages({ ...pages, current: 1 });
		queryGoodsList(query, { ...pages, current: 1 });
	}, [updateTime]);

	//初始执行一下计算高度的函数
	useEffect(() => {
		handleSetHeight();
	}, [goodsType]);

	//计算表格的滚动高度
	const handleSetHeight = () => {
		try {
			const sumHeight = document.getElementById("sectionContent").clientHeight;
			const searchHeight = divEl && divEl.current ? divEl.current.clientHeight : 0;
			const btnHeight = btnEl && btnEl.current ? btnEl.current.clientHeight + 28 : 0;
			const otherHeight = 162; //表头的高度和底部分页高度再加8以及padding值等;
			const finalHeight = sumHeight - (searchHeight + btnHeight + otherHeight);
			setScrollHeight(finalHeight);
		} catch (e) {
			console.log(e);
		}
	};

	//监听窗口尺寸变化计算一下高度
	useEventListener(window, "resize", handleSetHeight);

	//获取商品列表
	const queryGoodsList = async (query, pagination) => {
		setLoading(true);
		setGoodsList([]);
		// 查询条件收尾去空格
		const params = {
			...query,
			current: pagination.current,
			size: pagination.pageSize
			// createTime: updateTime,
		};
		const { data, success } = await getSystemGoodList(params);
		if (success) {
			const { records = [], total = 0 } = data;
			setGoodsList(records);
			setPages({
				...pagination,
				total
			});
		}
		setLoading(false);
	};

	//渲染操作列的内容
	const handleRenderOpera = record => {
		if (record.matchType == 0) {
			return null;
		} else {
			return (
				<div style={{ display: "flex", flexDirection: "column" }}>
					{goodsType != 3 && (
						<span onClick={() => handleSetGoodsType(3, record)} className="common-color2">
							设为库存商品
						</span>
					)}
					{goodsType != 1 && roleType != "daifa" && (
						<span onClick={() => handleSetGoodsType(1, record)} className="common-color2">
							设为自发拿货商品
						</span>
					)}
					{goodsType != 2 && record.daiFaflage && (
						<span onClick={() => handleSetGoodsType(2, record)} className="common-color2">
							设为代发拿货商品
						</span>
					)}
					{goodsType != 4 && record.flage && (
						<span onClick={() => handleSetGoodsType(4, record)} className="common-color2">
							设为供应商直发商品
						</span>
					)}
				</div>
			);
		}
	};

	const columns = [
		{
			title: "系统商品",
			dataIndex: "status",
			key: "status",
			width: 200,
			render: (text, record) => <SystemTableGoods hasGoodsCode={true} item={record} />
		},
		{
			title: "款式编码",
			dataIndex: "spuId",
			key: "spuId",
			width: 120,
			render: text => <span className="table-weight-text">{text}</span>
		},
		// {
		// 	title: '商品编码',
		// 	dataIndex: 'skuId',
		// 	key: 'skuId',
		// 	width: 120,
		// 	render: text => (
		// 		<span className="table-weight-text">{text}</span>
		// 	)
		// },
		{
			title: "价格",
			dataIndex: "goodsPrice",
			key: "goodsPrice",
			width: 80,
			render: text =>
				text && (
					<span className="table-weight-text" style={{ color: "#FF2D51" }}>
						¥{formatAmount(text)}
					</span>
				)
		},
		{
			title: "匹配状态",
			dataIndex: "matchType",
			key: "matchType",
			width: 80,
			render: (text, record) => (record.matchType == 0 ? <span>未匹配</span> : <span>已匹配</span>)
		},
		{
			title: "所属供应商",
			dataIndex: "zjfStoreName",
			key: "zjfStoreName",
			width: 120
		},
		{
			title: "分配发货渠道",
			dataIndex: "channelName",
			key: "channelName",
			width: 120,
			render: (text, record) => (
				<span>
					{text}
					{goodsType != 4 && record.isCarefullySelected != "1" && (
						<EditOutlined
							className="common-color2"
							onClick={() => handleEditChannel(record)}
							style={{ cursor: "pointer", fontSize: "16px" }}
						/>
					)}
				</span>
			)
		},
		{
			title: "合格证名称",
			dataIndex: "cofcTemplateName",
			key: "cofcTemplateName",
			width: 150,
			render: (text, record) => (
				<span>
					<Popover
						content={
							<div className="custom-ant-popver-content">
								{text}({record.width}*{record.height}mm)
							</div>
						}
					>
						<div className="textOverflowMultiTwo">
							{text ? (
								<span>
									{text}({record.width}*{record.height}mm)
								</span>
							) : (
								""
							)}
						</div>
					</Popover>
				</span>
			)
		},
		{
			title: "拿货模板名称",
			dataIndex: "takeTemplateName",
			key: "takeTemplateName",
			width: 150,
			render: (text, record) => (
				<span>
					<Popover content={<div className="custom-ant-popver-content">{text}</div>}>
						<div className="textOverflowMultiTwo">{text}</div>
					</Popover>
				</span>
			)
		},
		{
			title: "操作",
			dataIndex: "endTime",
			key: "endTime",
			fixed: "right",
			width: 120,
			render: (text, record) => handleRenderOpera(record)
		}
	];

	// 点击智能设置事件
	const setGoodsMind = () => {
		setVisible(2);
	};

	//单条点击设置渠道
	const handleEditChannel = val => {
		setItem(val);
		setVisible(3);
	};

	//点击设拿货模板
	const setTakeGoodsTemplate = () => {
		if (selectRowkeys.length > 0) {
			setVisible("takeGoodsTemplate");
		} else {
			Modal.info({ centered: true, okText: "知道了", content: <div>请先勾选再进行该操作！</div>, onOk() {} });
		}
	};

	//点击删除拿货模板
	const delTakeGoodsTemplate = () => {
		if (selectRowkeys.length > 0) {
			confirm({
				title: "确认信息",
				icon: <ExclamationCircleOutlined />,
				content: "是否确认删除所设的拿货模板？",
				cancelText: "取消",
				okText: "确定",
				onOk() {
					delTakeGoodsTemplateGoods();
				}
			});
		} else {
			Modal.info({ centered: true, okText: "知道了", content: <div>请先勾选再进行该操作</div>, onOk() {} });
		}
	};

	//批量删除拿货模板
	const delTakeGoodsTemplateGoods = async () => {
		setLoading(true);
		const { success } = await delTakeTemplate({
			ids: selectRowkeys.join(","),
			type: 1
		});
		if (success) {
			message.success("删除拿货模板成功！");
			queryGoodsList(query, { ...pages, current: 1 });
		}
		setLoading(false);
	};

	//点击设合格证
	const setCertificate = () => {
		if (selectRowkeys.length > 0) {
			setVisible("certificate");
		} else {
			Modal.info({ centered: true, okText: "知道了", content: <div>请先勾选再进行该操作</div>, onOk() {} });
		}
	};

	//点击删除合格证
	const delCertificate = () => {
		if (selectRowkeys.length > 0) {
			confirm({
				title: "确认信息",
				icon: <ExclamationCircleOutlined />,
				content: "是否确认删除所设的合格证模板？",
				cancelText: "取消",
				okText: "确定",
				onOk() {
					delCertificateGoods();
				}
			});
		} else {
			Modal.info({ centered: true, okText: "知道了", content: <div>请先勾选再进行该操作</div>, onOk() {} });
		}
	};

	//批量删除合格证
	const delCertificateGoods = async () => {
		setLoading(true);
		const { success } = await delUpCertificate({
			ids: selectRowkeys.join(","),
			type: 1
		});
		if (success) {
			message.success("删除合格证成功！");
			queryGoodsList(query, { ...pages, current: 1 });
		}
		setLoading(false);
	};

	//单个设置商品
	const handleSetGoodsType = (val, item) => {
		const goodsArr = [null, "自发拿货商品", "代发拿货商品", "库存商品", "供应商直发商品"];
		confirm({
			title: "确认信息",
			icon: <ExclamationCircleOutlined />,
			content: `是否确认设为${goodsArr[val]}？`,
			cancelText: "取消",
			okText: "确定",
			onOk() {
				handleCheckGoods(val, item);
			}
		});
	};

	//检测是否有对应的匹配网店商品
	const handleCheckGoods = async (val, item) => {
		const goodsArr = [null, "自发拿货商品", "代发拿货商品", "库存商品", "供应商直发商品"];
		setLoading(true);
		const { success, data } = await affectNums({
			zjfGoodsMatchIds: item.zjfGoodsMatchId ? item.zjfGoodsMatchId : 0
		});
		setLoading(false);
		if (success) {
			if (data <= 1) {
				setGoodsType(val, item);
			} else {
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: `检测到该网店商品匹配的供应商商品所对应的网店商品和系统商品有${
						data - 1
					}个，它们的商品类型会同时修改，请确认是否设为${goodsArr[val]}？`,
					cancelText: "取消",
					okText: "确定",
					onOk() {
						setGoodsType(val, item);
					}
				});
			}
		}
	};

	//批量检测是否有对应的匹配网店商品
	const handleBatchCheckGoods = async val => {
		const goodsArr = [null, "自发拿货商品", "代发拿货商品", "库存商品", "供应商直发商品"];
		const arr = [];
		for (let i in selectRowkeys) {
			const obj = find(goodsList, ["id", selectRowkeys[i]]);
			arr.push(obj.zjfGoodsMatchId);
		}
		setLoading(true);
		const { success, data } = await affectNums({
			zjfGoodsMatchIds: arr.join(",")
		});
		setLoading(false);
		if (success) {
			if (data <= 1) {
				handleBatchGoodsType(val);
			} else {
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: `检测到该网店商品匹配的供应商商品所对应的网店商品和系统商品有${
						data - 1
					}个，它们的商品类型会同时修改，请确认是否设为${goodsArr[val]}？`,
					cancelText: "取消",
					okText: "确定",
					onOk() {
						handleBatchGoodsType(val);
					}
				});
			}
		}
	};

	//设置商品类型
	const setGoodsType = async (val, item) => {
		setLoading(true);
		const obj = {
			ids: item.id + "",
			zjfGoodsMatchIdS: item.zjfGoodsMatchId + "",
			type: val
		};
		setLoading(false);
		const { success, data = {} } = await changeSysGoodsType(obj);
		if (success) {
			message.success("操作成功");
			handleData(1, item);
			const { ecGoodsIds = [], sysGoodsIds = [] } = data;
			getChannelStatistic(val, ecGoodsIds, false, 1, sysGoodsIds);
		}
	};

	// 商品类型修改对订单的影响
	const getChannelStatistic = async (type, ecGoodsIds, isAll, orderLength, sysGoodsIds) => {
		setLoading(true);
		const params = {
			type,
			ecGoodsIds: ecGoodsIds.toString(),
			platType: 1,
			ecSysGoodsIds: sysGoodsIds.toString()
		};
		const { success, data = 0 } = await queryChannelStatistic(params);
		if (success && data > 0) {
			confirm({
				title: <p className="common-color13">确认信息</p>,
				icon: <ExclamationCircleOutlined />,
				content: (
					<div>
						<p style={{ marginRight: "20px" }}>
							原{isAll ? orderLength + "个" : ""}商品已匹配待审核{data}
							条订单，修改商品类型可能会影响这些订单，请确认是否需要影响？
						</p>
						<p className="common-color9">注：</p>
						<p className="common-color9">①否：修改商品类型，将不影响订单页面的旧订单的商品类型</p>
						<p className="common-color9">
							②是：修改商品类型，将会使“待审核”的订单商品的商品类型修改为最新的商品类型，如果订单的发货渠道与商品渠道不一致，则会自动拆单
						</p>
					</div>
				),
				cancelText: "取消",
				okText: "确定",
				onOk() {
					handleOrderUpdate(params);
				}
			});
		}
		setLoading(false);
	};

	// 修改商品类型的提交更新
	const handleOrderUpdate = async params => {
		setLoading(true);
		const { success } = await updateOrderGoods(params);
		if (success) {
			message.success("更新成功");
		}
		setLoading(false);
	};

	//点击批量设置
	const handleClick = val => {
		if (selectRowkeys.length > 0) {
			if (val == 3) {
				//批量设置发货渠道
				setVisible(val);
			} else if (val == 4) {
				//批量设为自发拿货
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: "是否确认批量设为自发拿货？",
					cancelText: "取消",
					okText: "确定",
					onOk() {
						handleBatchCheckGoods(1);
					}
				});
			} else if (val == 5) {
				//批量设为代发拿货
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: "是否确认批量设为代发拿货？",
					cancelText: "取消",
					okText: "确定",
					onOk() {
						handleBatchCheckGoods(2);
					}
				});
			} else if (val == 6) {
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: "是否确认批量设为库存商品？",
					cancelText: "取消",
					okText: "确定",
					onOk() {
						handleBatchCheckGoods(3);
					}
				});
			} else if (val == 7) {
				confirm({
					title: "确认信息",
					icon: <ExclamationCircleOutlined />,
					content: "是否确认批量设为供应商直发？",
					cancelText: "取消",
					okText: "确定",
					onOk() {
						handleBatchCheckGoods(4);
					}
				});
			} else {
				return;
			}
		} else {
			message.info("请先选择需要批量操作的订单！");
		}
	};

	//批量设置自发（type=1）、代发(type=2)、库存商品(type =3)拿货、供应商直发(type =4)
	const handleBatchGoodsType = async val => {
		setLoading(true);
		const arr = [];
		for (let i in selectRowkeys) {
			const obj = find(goodsList, ["id", selectRowkeys[i]]);
			arr.push(obj.zjfGoodsMatchId);
		}

		const obj = {
			ids: selectRowkeys.join(","),
			zjfGoodsMatchIdS: arr.join(","),
			type: val
		};

		const { success, data: data1 = {} } = await changeSysGoodsType(obj);
		setLoading(false);
		if (success) {
			message.success("操作成功");
			//需要处理下数据
			handleData(2);
			const { ecGoodsIds = [], sysGoodsIds = [] } = data1;
			getChannelStatistic(val, ecGoodsIds, true, selectRowkeys.length, sysGoodsIds);
		}
	};

	//处理数据
	const handleData = (val, obj) => {
		if (val == 1) {
			//单个处理
			const arr = [...goodsList];
			remove(arr, v => v.id == obj.id);
			setGoodsList(arr);
			if (selectRowkeys.includes(obj.id)) {
				const arr = pull([...selectRowkeys], obj.id);
				setSelectRowkeys(arr);
			}
		} else {
			//批量处理
			const arr = [...goodsList];
			for (let i in selectRowkeys) {
				const id = selectRowkeys[i];
				remove(arr, v => v.id == id);
			}
			setGoodsList(arr);
			setSelectRowkeys([]);
		}
	};

	//表格数据
	const TableProps = {
		data: goodsList,
		columns,
		rowKey: "id",
		scroll: { x: 840, y: scrollHeight },
		rowSelection: {
			type: "checkbox",
			fixed: true,
			selectedRowKeys: selectRowkeys,
			onChange: selectRowKeys => {
				setSelectRowkeys(selectRowKeys);
			}
		}
	};

	// 顶部按钮
	const renderTableBtn = () => (
		<div className="common-table-header-btn" ref={btnEl}>
			<Button style={{ marginRight: "8px" }} onClick={setGoodsMind}>
				商品渠道智能设置
			</Button>
			{goodsType != 3 && (
				<Button style={{ marginRight: "8px" }} onClick={() => handleClick(6)}>
					批量设为库存
				</Button>
			)}
			{goodsType != 1 && roleType != "daifa" && (
				<Button style={{ marginRight: "8px" }} onClick={() => handleClick(4)}>
					批量设为自发拿货
				</Button>
			)}
			{goodsType != 2 && (
				<Button style={{ marginRight: "8px" }} onClick={() => handleClick(5)}>
					批量设为代发拿货
				</Button>
			)}
			{goodsType != 4 && (
				<>
					<Button style={{ marginRight: "8px" }} onClick={() => handleClick(7)}>
						批量设为供应商直发
					</Button>
					<Button style={{ marginRight: "8px" }} onClick={() => handleClick(3)}>
						批量修改发货渠道
					</Button>
				</>
			)}
			<Button style={{ marginRight: "8px" }} onClick={() => setCertificate()}>
				设合格证
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => delCertificate()}>
				删除合格证
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => setTakeGoodsTemplate()}>
				设拿货模板
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => delTakeGoodsTemplate()}>
				删除拿货模板
			</Button>
		</div>
	);

	//接口级别请求数据
	const getGoodsData = async (bool, obj = {}, arr) => {
		const { data, success } = await getSystemGoodList({
			ids: bool ? obj.id : selectRowkeys.join(","),
			deliverType: goodsType,
			page: 1,
			pageSize: 100
		});
		if (success) {
			const { records = [] } = data;
			for (let i in records) {
				const index = findIndex(arr, ["id", records[i].id]);
				arr[index] = records[i];
			}
			setGoodsList(arr);
		}
	};

	//智能商品弹框设置
	const SmartSetChannelProps = {
		visible: visible == 2,
		roleType,
		handleOk() {
			setVisible(1);
		},
		handleCancel() {
			setVisible(1);
		}
	};

	//设置发货渠道
	const EditChannelModalProps = {
		type: goodsType,
		item,
		visible: visible == 3,
		ids: selectRowkeys.join(","),
		handleOk(bool, item) {
			const arr = [...goodsList];
			getGoodsData(bool, item, arr);
			setItem({});
			setVisible(1);
		},
		handleCancel() {
			setItem({});
			setVisible(1);
		}
	};

	//设合格证
	const CertificateModalProps = {
		type: goodsType,
		visible: visible == "certificate",
		ids: selectRowkeys,
		handleCancel() {
			setVisible(1);
		},
		handleOk() {
			queryGoodsList(query, { ...pages, current: 1 });
			setVisible(1);
		}
	};

	//设拿货模板
	const TakeGoodsTemplateModalProps = {
		type: goodsType,
		visible: visible == "takeGoodsTemplate",
		ids: selectRowkeys,
		handleCancel() {
			setVisible(1);
		},
		handleOk() {
			queryGoodsList(query, { ...pages, current: 1 });
			setVisible(1);
		}
	};

	//分页数据
	const PageProps = {
		pagination: pages,
		//分页变化
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
			queryGoodsList(query, obj);
		}
	};

	return (
		<>
			{renderTableBtn()}
			<CommonTable {...TableProps} />
			{visible == 2 && <SmartSetChannel {...SmartSetChannelProps} />}
			{visible == 3 && <EditChannelModal {...EditChannelModalProps} />}
			{visible == "certificate" && <CertificateModal {...CertificateModalProps} />}
			{visible == "takeGoodsTemplate" && <TakeGoodsTemplateModal {...TakeGoodsTemplateModalProps} />}
			<FooterToolbar>
				<CommonPage {...PageProps} />
			</FooterToolbar>
			<CommonLoading loading={loading} />
		</>
	);
};
